import { message } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import type { AuthRoleEditItem, AuthRoleTableListItem } from '../data';
import type { AuthPermission } from '../data';
import {
  editAdminRole,
  fetchConfigurableAuthPermission,
  queryAdminRoleDetail,
  updateAdminRoleAccesses,
} from '@/pages/System/Auth/AuthRole/service';
import { SUCCESS_CODE } from '@/utils/request';
import type { ProFormInstance } from '@ant-design/pro-form';
import ProForm, { ModalForm, ProFormText } from '@ant-design/pro-form';
import AuthPermissionConfiguration from '@/pages/System/Auth/AuthRole/components/AuthPermissionConfiguration';

interface EditFormProps {
  item: AuthRoleTableListItem;
  onSubmit: (values: AuthRoleEditItem) => void;
  modalVisible: boolean;
  onVisibleChange: (visible: boolean) => void;
}

const EditForm: React.FC<EditFormProps> = (props) => {
  const [data, setData] = useState<AuthRoleTableListItem>();
  const [permissions, setPermissions] = useState<AuthPermission[]>([]);

  const { onSubmit, onVisibleChange, modalVisible, item } = props;

  const formRef = useRef<ProFormInstance>();

  formRef.current?.setFieldsValue(item);

  const onModalOk = async () => {
    const fieldsValue = (await formRef.current?.validateFields()) as AuthRoleEditItem;

    fieldsValue.id = item?.id;

    const hide = message.loading('正在修改');

    try {
      const res = await editAdminRole(fieldsValue);
      if (res.code === SUCCESS_CODE) {
        hide();
        message.success('修改成功');
        onSubmit(fieldsValue);
      } else {
        message.error(res.message || '修改失败');
      }
      return true;
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
      onSubmit(fieldsValue);
      return false;
    }
  };

  useEffect(() => {
    queryAdminRoleDetail({ id: item.id }).then((res) => {
      if (res && res.success) {
        setData(res.data);
      }
    });

    fetchConfigurableAuthPermission({}).then((res) => {
      setPermissions(res.data || []);
    });
  }, [item]);

  return (
    <ModalForm
      title="修改账号角色"
      visible={modalVisible}
      formRef={formRef}
      width={600}
      onVisibleChange={(value) => {
        onVisibleChange(value);
      }}
      onFinish={onModalOk}
    >
      <ProFormText name="name" label="角色名称" rules={[{ required: true, message: '必填' }]} />

      <ProForm.Item name="access" label="权限配置">
        <AuthPermissionConfiguration
          sourceValue={permissions}
          defaultValue={data?.permissions}
          id={item?.id}
          onChange={async (values) => {
            await updateAdminRoleAccesses({
              roleId: item?.id,
              permissions: values,
            });
          }}
        />
      </ProForm.Item>
    </ModalForm>
  );
};
export default EditForm;
